import AntModal from '@/components/pt/dialog/AntModal'
import { getBizInventoryOrder, addBizInventoryOrder, updateBizInventoryOrder } from '@/api/biz/bizInventoryOrder'
import SelectUser from "@/components/pt/selectUser/SelectUser";
import SelectDept from "@/components/pt/selectDept/SelectDept";
import BizProduct from "@/views/biz/bizorder/modules/BizProduct";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import {listBizWarehouseSpaceByWarehouseId} from "@/api/biz/bizWarehouseSpace";
import {listBizProductInventory} from "@/api/biz/bizProductInventory"
import tableDragResizeMixin from '@/mixins/tableDragResizeMixin'
import {randomUUID} from '@/utils/util';

export default {
  name: 'CreateForm',
  mixins:[tableDragResizeMixin],
  props: {
    statusOptions: {
      type: Array,
      required: true
    },
    warehouseIdOptions: {
      type: Array,
      required: false
    }

  },
  components: {
    AntModal,
    SelectUser,
    SelectDept,
    BizProduct,
    AdvanceTable
  },
  data () {
    return {
      disabledCreated:true,
      showProductModal:false,
      multiple:false,
      open: false,
      closeDialog: true,
      spinning: false,
      delayTime: 100,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      loading: false,
      disabled: false,
      total: 0,
      id: undefined,
      spaceList:[],//
      formTitle: '添加库存盘点单',
      // 表单参数
      form: {},
      rules: {
        tenantId: [{ required: true, message: '租户id不能为空', trigger: 'blur' }],
        warehouseId: [{ required: true, message: '请选择仓库', trigger: 'blur' }]
      },
      columns: [
        {
          title: '存货编码',
          dataIndex: 'productCode',
          align: 'center',
          width: '15%'
        },
        {
          title: '仓位',
          dataIndex: 'spaceId',
          align: 'center',
          width: '5%',
          scopedSlots: {
            customRender: 'spaceIdSlot'
          },
        },
        {
          title: '库存',
          dataIndex: 'stock',
          align: 'center',
          width: '5%'
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          align: 'center',
          width: '5%'
        },
        {
          title: '规格',
          dataIndex: 'spec',
          align: 'center',
          width: '10%'
        },
        {
          title: '颜色',
          dataIndex: 'color',
          align: 'center',
          width: '8%'
        },
        {
          title: '数量',
          dataIndex: 'number',
          align: 'center',
          scopedSlots: {
            customRender: 'numberSlot'
          },
          width: '7%'
        },
        {
          title: '单位',
          dataIndex: 'unit',
          align: 'center',
          scopedSlots: {
            customRender: 'unitSlot'
          },
          width: '7%'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          align: 'center',
          scopedSlots: {
            customRender: 'remarkSlot'
          },
          width: '10%'
        }
      ],
      list: [],
      selectedRowKeys:[],
      ids:[],
    }
  },
  filters: {},
  created () {
    this.initColumnsSetting('stockDetail')
  },
  computed: {},
  watch: {},
  mounted () {},
  methods: {
    onClose () {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,
        receiveCode: undefined,

        receiveDate: undefined,

        receiveUserId: undefined,

        receiveUserName: undefined,

        tenantId: undefined,

        status: '0',

        detailList : [],

      }
    },
    /**
     * 
     * @param {string} value 
     * @param {obj} record 
     * @param {number} index 
     */
    changeSpace(value,record,index){
      let params={
        warehouseId:this.form.warehouseId,
        productId: record.id,
        spaceId:value
      }
      listBizProductInventory(params).then(res=>{
        let data = res.data.list
        if(data.length === 0){
          record.stock = 0
          this.form.detailList.splice(index,1,record)
        }else if(data.length === 1){
          record.stock = data[0].stock
          this.form.detailList.splice(index,1,record)

        }else{
          console.log('库存异常 :>> ');
        }
      })
    },
    /**
     * 选择仓库
     * @returns 
     */
    selectWarehouse() {
      if(!this.form.warehouseId) {
        return;
      }
      listBizWarehouseSpaceByWarehouseId(this.form.warehouseId).then(res=>{
        this.spaceList=res.data;
        // if(this.spaceList && this.spaceList.length>0) {
        //   this.form.detailList.forEach(item=>{
        //     item.spaceId=this.spaceList[0].id;
        //   });
        // }
      });
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      this.open = true
      this.formTitle = '添加库存盘点单'
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset()
      this.open = true
      this.spinning = !this.spinning
      const bizReceiveOrderId = row.id
      getBizInventoryOrder(bizReceiveOrderId).then(response => {
        this.form = response.data
        this.form.receiveUserId = { ids: this.form.inventoryUserId, names: this.form.inventoryUserName }
        this.form.detailList = this.form.detailList.map(v=>(v.unit = +v.unit,v.uuid = randomUUID(),v))
        this.formTitle = '修改库存盘点单'
        this.spinning = !this.spinning
        // 根据仓库获取仓位信息
        this.selectWarehouse()
      })
    },
    /** 提交按钮 */
    submitForm: function (closeDialog) {
      this.closeDialog = closeDialog
      this.disabled = true
      this.$refs.form.validate(valid => {
        if (valid) {
          const saveForm = JSON.parse(JSON.stringify(this.form))
          if (this.form.receiveUserId !== undefined) {
            saveForm.inventoryUserId = this.form.receiveUserId.ids
            saveForm.inventoryUserName = this.form.receiveUserId.names
          }
          if (this.form.id !== undefined) {
            updateBizInventoryOrder(saveForm).then(response => {
              this.$message.success('更新成功', 3)
              this.open = false
              this.$emit('ok')
              this.$emit('close')
              this.disabled = false
            })
          } else {
            addBizInventoryOrder(saveForm).then(response => {
              this.$message.success('新增成功', 3)
              this.open = false
              this.$emit('ok')
              this.$emit('close')
              this.disabled = false
            })
          }
        } else {
          this.disabled = false
          return false
        }
      })
    },
    back () {
      const index = '/biz/bizreceiveorder/index'
      this.$router.push(index)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length == 1
      this.multiple = selectedRowKeys.length
    },
    handleSubUpdate() {

    },
    handleSubDelete(row) {
      var that = this
      const productIds = row.id || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk:()=>{
          this.form.detailList = this.form.detailList.filter(v=>!this.selectedRowKeys.includes(v.uuid))
          that.$message.success(
            '删除成功',
            3
          )
          that.onSelectChange([], [])
          return;
        },
        onCancel () {}
      })
    },
    handleAddProduct() {
      this.showProductModal = true
      this.$nextTick(() => {
        this.$refs.bizProduct.handleAddProduct(this.list);
      })
    },
    inputChange(){
      console.log('this.form.detailList :>> ', this.form.detailList);
    },
    selectProduct(selectedRows) {
      this.form.detailList = [...this.form.detailList,...selectedRows];
      this.form.detailList.forEach(item=>{
        item.unitList = [];
        item.unitList.push({
          key: 1,
          name: item.unit
        })
        item.unitList.push({
          key: 2,
          name: item.assistUnitA
        })
        item.unitList.push({
          key: 3,
          name: item.assistUnitB
        })
        item.number = item.number || 0;
        item.tempSalePrice = item.salePrice;
        if (item.defaultWarehousingUnit == 2) {
          item.unit = 2
          item.unitPrice = item.salePriceA
        } else if (item.defaultWarehousingUnit == 3) {
          item.unit = 3
          item.unitPrice = item.salePriceB
        } else {
          item.unit = 1;
          item.unitPrice=item.salePrice;
        }
        item.totalAmount = 0.00;
        item.uuid = randomUUID()
      })
      
      console.log('this.form.detailList :>> ', this.form.detailList);
      this.$forceUpdate();

    },
    handleChange(info) {
      if (info.file.status == 'done') {
        this.fileList=info.fileList;
      }
    },
    handleRemove(info) {
      this.fileList=this.fileList.filter(function(item) {
        return item.uid != info.uid
      })
    },

    changeUnit(record) {
      // if (record.unit == 1) {
      //   record.unitPrice = record.tempSalePrice;
      // } else if (record.unit == 2) {
      //   record.unitPrice = record.salePriceA;
      // } else if (record.unit == 3) {
      //   record.unitPrice = record.salePriceB;
      // }
      record.totalAmount = record.unitPrice * record.number;
      this.$forceUpdate();
    },
    selectUnit(record) {
      if (record.unit == 1) {
        record.unitPrice = record.purchasesPrice;
      } else if (record.unit == 2) {
        record.unitPrice = record.purchasesPriceA;
      } else if (record.unit == 3) {
        record.unitPrice = record.purchasesPriceB;
      }
      record.totalAmount = record.unitPrice * record.number;
      this.$forceUpdate();
    },
    
    /**
     * 设置table的row的class
     * @param {obj} row 
     * @param {number} index 
     */
     getRowClassName(row,index){
      let arr = this.form.detailList.filter(v=>v.productCode === row.productCode)
      if (arr.length > 1) {
        console.log('222 :>> ', 222);
        return 'multiple_table_row'
      }
    },

  }
}
